package observer.practice_03;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.log4j.Logger;

/**
 * @author yi qiang
 * @date 2021/11/4 1:55
 */
public class PaySubject implements Subject {

    private final Logger log= Logger.getLogger(PaySubject.class);

    private static final Map<String, Observer> OBSERVERS = new ConcurrentHashMap<>();

    public Map<String, Observer> getObservers(){
        return OBSERVERS;
    }

    @Override
    public Map<String, Observer> register(Observer observer) {
        OBSERVERS.put(observer.getName(), observer);
        return OBSERVERS;
    }

    @Override
    public boolean remove(String name) {
        Observer remove = OBSERVERS.remove(name);
        return remove != null;
    }

    @Override
    public void broadcast(String msg) {
        OBSERVERS.forEach((k,v)->{
            try{
                v.handle(msg);
            }catch(Exception e){
                log.info(e.getMessage(),e);
            }
        });
    }
}
